<template>
    <view>
        <template v-if="sms.length > 0">
            <sms-item :sms="sms" />
        </template>

        <template v-else>
            <view class="w-100 flex justify-center align-center" style="height: 50vh;">
                <uni-load-more :contentText="contentText" status="no-more" />
            </view>
        </template>
    </view>
</template>

<script setup>
    import {
        ref,
        computed,
        onMounted,
        reactive
    } from 'vue';
    import {
        useStore
    } from 'vuex';
    import env from "@/env.js";
    import envConfig from '@/env_config.js';
    import $T from '@/common/time.js';

    const store = useStore();
    const config = envConfig[env];
    const sms = computed(() => {
        const {
            user,
            sms
        } = store.state;
        return sms.filter(item => Number(item.user_id) === Number(user.id));
    });

    const contentText = reactive({
        contentdown: "上拉显示更多",
        contentrefresh: "正在加载...",
        contentnomore: "暂无数据"
    });

    // Method - 获取权限
    const requestPermissions = () => {
        const permissionArr = ['android.permission.READ_SMS', 'android.permission.RECEIVE_SMS',
            'android.permission.RECEIVE_MMS'
        ];

        plus.android.requestPermissions(permissionArr, function(e) {
            if (e.deniedAlways.length > 0) { //权限被永久拒绝
                // 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
                console.log('Always Denied!!! ' + e.deniedAlways.toString());
            }
            if (e.deniedPresent.length > 0) { //权限被临时拒绝
                // 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
                console.log('Present Denied!!! ' + e.deniedPresent.toString());
            }
            if (e.granted.length > 0) { //权限被允许
                //调用依赖获取定位权限的代码
                console.log('Granted!!! ' + e.granted.toString());
            }
        }, function(e) {
            console.log('Request Permissions error:' + JSON.stringify(e));
        });
        monitor();
    }

    // Method - 监听
    const monitor = () => {
        let callbacks = [];
        let receiver;
        let filter;
        let main;
        let isInit = false;
        let isRegistered = false;
        let isOlderVersion = false;

        let init = function(callback) {
            //仅支持Android版本  
            if (plus.os.name !== 'Android') {
                return;
            }
            try {
                let version = plus.runtime.innerVersion.split('.');
                isOlderVersion = parseInt(version[version.length - 1]) < 22298;
                main = plus.android.runtimeMainActivity();
                let Intent = plus.android.importClass('android.content.Intent');
                let IntentFilter = plus.android.importClass('android.content.IntentFilter');
                let SmsMessage = plus.android.importClass('android.telephony.SmsMessage');
                let receiverClass = 'io.dcloud.feature.internal.reflect.BroadcastReceiver';
                if (isOlderVersion) {
                    receiverClass = 'io.dcloud.feature.internal.a.a';
                }
                filter = new IntentFilter();

                let onReceiveCallback = function(context, intent) {
                    try {
                        let action = intent.getAction();
                        if (action == "android.provider.Telephony.SMS_RECEIVED") {
                            let pdus = intent.getSerializableExtra("pdus");
                            let msgs = [];
                            for (let i = 0, len = pdus.length; i < len; i++) {
                                msgs.push(SmsMessage.createFromPdu(pdus[i]));
                            }
                            for (let i = 0, len = callbacks.length; i < len; i++) {
                                callbacks[i](msgs);
                            }
                        }
                    } catch (e) {
                        console.log(' -- on receive callback error: ', JSON.stringify(e));
                    }
                }
                receiver = plus.android.implements(receiverClass, {
                    a: onReceiveCallback,
                    onReceive: onReceiveCallback
                });
                filter.addAction("android.provider.Telephony.SMS_RECEIVED");
                callback && callback();
            } catch (e) {}
        }
        //注册短信监听  
        let register = function(callback) {
            callbacks.push(callback);
            if (!isInit) {
                isInit = isRegistered = true;
                init(function() {
                    setTimeout(function() {
                        try {
                            if (isOlderVersion) {
                                main.a(receiver, filter);
                            } else {
                                main.registerReceiver(receiver, filter); //注册监听  
                            }
                        } catch (e) {
                            console.log('注册监听 error:' + JSON.stringify(e));
                        }
                    }, 300);
                });

            } else if (!isRegistered) {
                try {
                    if (isOlderVersion) {
                        main.a(receiver, filter);
                    } else {
                        main.registerReceiver(receiver, filter); //注册监听  
                    }
                } catch (e) {
                    console.log('注册失败监听' + JSON.stringify(e));
                }
            }
        };

        //注销监听，在登录成功或从登录页跳转到其它页面后调用  
        let unregister = function(callback, remove) {
            for (let i = 0, len = callbacks.length; i < len; i++) {
                if (callbacks[i] === callback) {
                    callbacks.splice(i, 1);
                }
            }
            if (remove && !callbacks.length) {
                if (main && isRegistered) {
                    try {
                        if (isOlderVersion) {
                            main.a(receiver);
                        } else {
                            main.unregisterReceiver(receiver);
                        }
                    } catch (e) {}
                    isRegistered = false;
                    console.log('unregisterReceiver', JSON.stringify(e));
                }
            }
        };

        const smsHandler = function(msgs) {
            //操作短信
            for (let i = 0, len = msgs.length; i < len; i++) {
                const address = msgs[i].getDisplayOriginatingAddress();
                const content = msgs[i].getDisplayMessageBody();
                const regex = /((?<=\【)(.+?)(?=\】))/g; // {} 中文大括号
                const _person = content.match(regex);
                const date = $T.dateFormat(new Date(), '{Y}-{MM}-{DD} {hh}:{ii}:{ss}')
                let person = '';

                if (_person && _person.length !== 0) {
                    person = _person[0];
                }
                const _sms = {
                    SmsName: address,
                    person,
                    SmsDate: date,
                    SmsContent: content
                };

                store.dispatch('createSms', _sms);
            }
        }
        register(smsHandler);
    }

    onMounted(() => {
        requestPermissions();
    });
</script>

<style>

</style>